package org.skatiger.jrove.component.core;

import java.io.IOException;
import java.util.Locale;

import org.skatiger.jrove.ViewContext;
import org.skatiger.jrove.component.UIComponentBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class FormatBase extends UIComponentBase {
    private static final Logger logger = LoggerFactory
            .getLogger(FormatBase.class);
    private String var; // 'var' attribute
    private String pattern; // 'pattern' attribute
    private Object value;

    public Object getValue() {
        return getPropertyValue("value", value);
    }

    public String getPattern() {
        return getPropertyValue("pattern", pattern);
    }

    public void setPattern(String pattern) {
        this.pattern = pattern;
    }

    public String getVar() {
        return getPropertyValue("var", var);
    }

    public void setVar(String var) {
        this.var = var;
    }

    public void setValue(Object value) {
        if (value == null) {
            return;
        }
        if (!isSupport(value.getClass())) {
            throw new IllegalArgumentException(this.getClass()
                    + " unsupported type of " + value.getClass());
        }
        this.value = value;
    }

    protected abstract boolean isSupport(Class<?> clazz);

    protected abstract String getFormatedValue();

    @Override
    public final void encodeBegin(ViewContext context) throws IOException {
    }

    @Override
    public final void encodeChildren(ViewContext context) throws IOException {
    }

    @Override
    public boolean getRendersChildren() {
        return true;
    }

    @Override
    public void encodeEnd(ViewContext context) throws IOException {
        super.encodeEnd(context);

        Object value = getValue();
        String var = getVar();
        if (value == null) {
            if (var != null) {
                context.removeAttribute(var);
            }
            return;
        }
        String formatted = getFormatedValue();
        if (var != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("set formatedValue with attributeName " + var);
            }
            context.setAttribute(var, formatted);
        } else {
            if (formatted != null) {
                context.getResponseWriter().writeText(formatted, "value");
            }
        }
    }

    protected Locale getLocale() {
        Locale locale = (Locale) getViewContext().getAttribute("locale");
        return locale;
    }
}
